package com.pactera.integral.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.pactera.integral.common.jpa.criteria.Criteria;
import com.pactera.integral.common.jpa.criteria.Restrictions;
import com.pactera.integral.common.repository.QueryResult;
import com.pactera.integral.common.repository.ResultMap;
import com.pactera.integral.dao.PerformanceScoreDao;
import com.pactera.integral.dao.UserDao;
import com.pactera.integral.dao.UserPerformanceScoreDao;
import com.pactera.integral.entity.PerformanceScore;
import com.pactera.integral.entity.User;
import com.pactera.integral.entity.UserPerformanceScore;
import com.pactera.integral.service.PerformanceScoreService;
import com.pactera.integral.util.SumScore;
import org.springframework.util.StringUtils;

@Service
public class PerformanceScoreServiceImpl implements PerformanceScoreService {

	@Autowired
	private PerformanceScoreDao performanceScoreDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserPerformanceScoreDao userPerformanceScoreDao;

	/**
	 * 添加或修改积分项
	 * 
	 * @param performanceScore
	 * @throws Exception
	 */
	@Override
	public void save(PerformanceScore performanceScore) throws Exception {
		PerformanceScore existingEntity = performanceScoreDao.findByCode(performanceScore.getCode());

		if (existingEntity != null) {
			if (!existingEntity.getId().equals(performanceScore.getId())) {
				// 不同的ID发现同样的Code视为已存在

				throw new Exception("积分编码已存在!");
			} else {
				existingEntity.setCategory(performanceScore.getCategory());
				existingEntity.setEnabled(performanceScore.isEnabled());
				existingEntity.setResult(performanceScore.getResult());
				existingEntity.setScore(performanceScore.getScore());
				existingEntity.setScoreType(performanceScore.getScoreType());
				existingEntity.setDetail(performanceScore.getDetail());
				existingEntity.setRemark(performanceScore.getRemark());

				performanceScoreDao.save(existingEntity);
			}
		} else {
			performanceScore.setEnabled(true);
			performanceScoreDao.save(performanceScore);
		}
	}

	/**
	 * 删除积分向
	 * 
	 * @param performanceScoreId
	 * @return Boolean
	 */
	@Override
	public Boolean delete(String performanceScoreId) {
		PerformanceScore performanceScore = performanceScoreDao.findById(performanceScoreId);
		performanceScore.setEnabled(false);
		performanceScoreDao.save(performanceScore);

		return Boolean.TRUE;
	}

	/**
	 * 积分向列表
	 * 
	 * @param param
	 * @param page
	 * @return Page<PerformanceScore>
	 */
	@Override
	public Page<PerformanceScore> pagePerformanceScore(Map<String, Object> param, Pageable page) {
		Criteria<PerformanceScore> criteria = new Criteria<PerformanceScore>();
		if (param != null) {
			criteria.add(Restrictions.eq("enabled", 1));
			criteria.add(Restrictions.eq("scoreType", (String) param.get("scoreType")));
			criteria.add(Restrictions.like("code", (String) param.get("code")));
			criteria.add(Restrictions.eq("category", (String) param.get("category")));

		}
		Page<PerformanceScore> p = performanceScoreDao.findAll(criteria, page);

		return p;
	}

	/**
	 * 积分向明细
	 * 
	 * @param id
	 * @return PerformanceScore
	 */
	@Override
	public PerformanceScore getperformanceScore(String id) {

		return performanceScoreDao.findById(id);
	}

	public List<List<PerformanceScore>> getListForShow() {
		String sqlKey = "getPerformanceCatagory";
		String category = "";
		QueryResult<ResultMap<String, Object>> categoryResult = performanceScoreDao.findMapListBySQLKey(sqlKey, null,
				null);
		ArrayList<List<PerformanceScore>> list = new ArrayList<List<PerformanceScore>>();
		for (int i = 0; i < categoryResult.getContent().size(); i++) {
			category = (String) categoryResult.getContent().get(i).get("CATEGORY");
			List<PerformanceScore> result = performanceScoreDao.findByCategory(category);
			list.add(result);
		}
		return list;
	}

	/**
	 * 自评绩效分
	 */
	@Override
	public Boolean addScore(String staffId, List<UserPerformanceScore> performanceScore) {
		User user = userDao.findByStaffId(staffId);
		String userId = user.getUserId();
		int year = 0;
		int month = 0;
		boolean isSum = false;
		UserPerformanceScore userPerformanceScoer = new UserPerformanceScore();
		for (int i = 0; i < performanceScore.size(); i++) {
			String submintId = performanceScore.get(i).getId();
			UserPerformanceScore existingScore = userPerformanceScoreDao.findById(submintId);
			//组长评分
			if (existingScore != null) {
				isSum = true;
				year = existingScore.getYear();
				month = existingScore.getMonth();
				existingScore.settLScore(performanceScore.get(i).gettLScore());
				userPerformanceScoreDao.save(existingScore);
			}else{
				userPerformanceScoer = performanceScore.get(i);
				userPerformanceScoer.setUserId(userId);
				userPerformanceScoreDao.save(userPerformanceScoer);
			}
		}		
		if (isSum) {
			SumScore.sum(staffId, year, month);
		}
		return Boolean.TRUE;
	}

	/**
	 * 查询本月度绩效分是否已录入
	 * 
	 * @param staffId
	 * @param month
	 * @param year
	 * @return
	 */
	public String checkUserPerformanceScore(String staffId, String month, String year) {
		User user = userDao.findByStaffId(staffId);
		String userId = user.getUserId();
		String sqlKey = "userPerformanceScore.searchByMonth";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("userId", userId);
		parameterMap.put("month", month);
		parameterMap.put("year", year);
		QueryResult<ResultMap<String, Object>> result = userPerformanceScoreDao.findMapListBySQLKey(sqlKey,
				parameterMap, null);
		if (result.getContent().size() > 0) {
			return "exist";
		}
		return "new";
	}
	
	/**
	 * 查询绩效分历史
	 * 
	 * @param staffId
	 * @return
	 */
	public List<ResultMap<String, Object>> getScoreHistory(String staffId) {
		User user = userDao.findByStaffId(staffId);
		String userId = user.getUserId();
		String sqlKey = "performanceScoreHistory.searchByUserId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("userId", userId);
		QueryResult<ResultMap<String, Object>> result = userDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}

	@Override
	public List<ResultMap<String, Object>> getUserId(String staffId,String userName,String year,String month) {
		String sqlKey = "memberPerformanceScore.searchByDepartmentCode";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		User uesr = userDao.findByStaffId(staffId);
		String departmentCode = uesr.getDepartmentCode();
		parameterMap.put("departmentCode", departmentCode);
		parameterMap.put("groupName", "Team Member");
		parameterMap.put("month", month);
		parameterMap.put("year", year);
		if(StringUtils.hasText(userName)){
			sqlKey = "memberPerformanceScore.searchByDepartmentCodeAndUsername";
			parameterMap.put("userName", userName);
		}
		QueryResult<ResultMap<String, Object>> result = userPerformanceScoreDao.findMapListBySQLKey(sqlKey, parameterMap,
				null);
		return result.getContent();
	}

	@Override
	public List<ResultMap<String,Object>> getDetailForShow(String staffId,String year,String month) {
		String sqlKey = "userPerformanceScoreDetail.searchByStaffId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("staffId", staffId);
		parameterMap.put("month", month);
		parameterMap.put("year", year);
		QueryResult<ResultMap<String, Object>> result = userDao.findMapListBySQLKey(sqlKey, parameterMap, null);
		return result.getContent();
	}
}
